package travelDream.managedBean;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Managed bean responsible of the authentication of the
 * registered users
 */
@ManagedBean(name = "loginManagedBean")
@ViewScoped
public class LoginManagedBean {
    private String email;
    private String password;
    private String requestedURL;
    private String errorMessage;
    private boolean isImpiegato = false;
    private boolean isAdmin = false;
    private boolean fromAmico = false;
    
    @PostConstruct
    public void init() {
    	isImpiegato = false;
        isAdmin = false;
        fromAmico = false;
        ExternalContext externalContext = FacesContext.getCurrentInstance()
                .getExternalContext();
        this.requestedURL = (String) externalContext.getRequestMap()
                .get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (this.requestedURL == null) {
            String baseUrl = "/utente/home.xhtml";
            if(isImpiegato) baseUrl = "/impiegato/home.xhtml";
            if(isAdmin) baseUrl = "/admin/home.xhtml";
            this.requestedURL = externalContext.getRequestContextPath()+baseUrl;
        } else {
            String originalQuery = (String) externalContext.getRequestMap()
                    .get(RequestDispatcher.FORWARD_QUERY_STRING);
            if (originalQuery != null) {
                this.requestedURL += "?" + originalQuery;
            }
        }
        if (requestedURL.contains("impiegato")){
            setImpiegatoLogin();
        }
        
        if (requestedURL.contains("admin")){
            setAdminLogin();
        }
        
        String paramAmico= externalContext.getRequestParameterMap().get("amico");
        
        if (paramAmico!= null && paramAmico.equals("true"))
        		this.setLoginPerAmico();
    }

    /**
     * This method offers the possibility to login
     * @throws IOException
     */
    public void login() throws IOException
    {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        try {
            request.login(this.email,this.password);
            if(externalContext.isUserInRole("IMPIEGATO") && (requestedURL.contains("utente") || requestedURL.contains("admin"))){
                context.addMessage(null, new FacesMessage("Not Authorized"));
                this.errorMessage = "Non autorizzato";
                request.logout();
            }
            else if(externalContext.isUserInRole("UTENTE") && (requestedURL.contains("impiegato") || requestedURL.contains("admin"))){
                context.addMessage(null, new FacesMessage("Not Authorized"));
                this.errorMessage = "Non autorizzato";
                request.logout();
            }
            else if(externalContext.isUserInRole("ADMIN") && (requestedURL.contains("impiegato") || requestedURL.contains("utente"))){
                context.addMessage(null, new FacesMessage("Not Authorized"));
                this.errorMessage = "Non autorizzato";
                request.logout();
            }
            else {
            externalContext.redirect(this.requestedURL);
            }
        } catch (ServletException e) {
            context.addMessage(null, new FacesMessage("Unknown login"));
            this.errorMessage = "Nome utente o password errate";
        }
    }

    /**
     * This method offers the possibility to logout
     * @return the JSF reference for redirect
     */
    public String logout(){
        String result="/login.xhtml?faces-redirect=true";

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
        try {
            request.logout();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        return result;
    }

    /*
   * GETTERS AND SETTERS
   * */

    
    
     public void logoutUnauthorized(){
        this.logout();
    }

    public boolean isFromAmico() {
		return fromAmico;
	}

    public void setFromAmico(boolean fromAmico) {
		this.fromAmico = fromAmico;
	}
    
    public void setLoginPerAmico() {
		this.fromAmico = true;
		this.isAdmin = false;
		this.isImpiegato = false;
	}

	public void setImpiegatoLogin(){
        isImpiegato = true;
    }
    
    public void setAdminLogin(){
        isAdmin = true;
    }
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public Boolean getIsImpiegato() {
        return isImpiegato;
    }
    
    public Boolean getIsAdmin() {
        return isAdmin;
    }
}